package com.hx.vending.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hx.vending.pay.*;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/4.
 */
public class PushUtils {
    private final Integer agentId = 1000005;//后台应用标识id

    private static Logger logger = Logger.getLogger(PushUtils.class);
    //应用密钥
    private final String secret = "B3fC_eYLT5Bm2L_-3gZ2Fa7etcA128o4FVUZbq-b0Rg";
    //private final String secret = "";//后台应用密钥
    public static PushUtils utils = null;
    // 企业id
    private final String companyId = "wwa176613437bd7326";//企业id
    //通讯录密钥，使用该密钥请求获取的token才有权限对通讯录进行操作
    private static String addressSecret = "S-b6swWXnok55CJZ7rwnU7r2myr6aSU0PpqhYX-uI_8";
    /**
     * 调用凭证，每次调用token后有效时间为两小时
     */
    private String ACCESS_TOKEN = null;

    public static PushUtils getInstance() {
        if (null == utils) {
            utils = new PushUtils();
        }
        return utils;
    }
    /**
     * 获取access_token
     * secret:使用哪个密钥进行url拼接获取token
     *
     * @return
     */
    public String getAccessToken(Integer secret){
        String value = null;
        if(secret == 1){
            value = this.secret;
        }else if(secret == 2){
            value = this.addressSecret;
        }
        String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s", companyId, value);
        URL u = null;
        Map jsonMap = new HashMap();
        try{
            u = new URL(url);
            HttpsURLConnection huconn = (HttpsURLConnection)u.openConnection();
            BufferedReader in = null;
            StringBuilder result = new StringBuilder();
            huconn.connect();
            in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            if (in != null) {
                in.close();
            }
            // 打印返回结果
            jsonMap = (Map) JSONObject.parse(result.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
        if ((Integer) jsonMap.get("errcode") == 0) {
            ACCESS_TOKEN = (String) jsonMap.get("access_token");
            //System.out.println("获取的AccessToken==========="+ACCESS_TOKEN);
            return ACCESS_TOKEN;
        } else {
            logger.error("------------------打印结果是:" + jsonMap + "-----------------------------------------");
            return null;
        }
    }

    /**
     * 发送连接请求
     * @param requestUrl 请求url
     * @param dataMap 请求体数据
     * @param requestMethod	请求的方法 POST/GET
     * @return
     */
    public Map<String, Object> sendRequest(String requestUrl, Map dataMap, String requestMethod){
        Map<String, Object> resultMap = new HashMap<>();
        //发送请求
        OutputStreamWriter out = null;
        InputStream is = null;
        URL url;
        try{
            url = new URL(requestUrl);// 创建连接
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod(requestMethod); // 设置请求方式

            String s = null;
            if (requestMethod.equals("POST")){
                connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
                s = JSON.toJSON(dataMap).toString();
                /*System.out.println("0000");*/
            }
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(s);
            out.flush();
            out.close();
            // 读取响应
            is = connection.getInputStream();
            int length = (int) connection.getContentLength();// 获取长度
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码
                resultMap = (Map<String, Object>) JSONObject.parse(result.toString());
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            try {
                if (null != is && null != out){
                    out.close();
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }


    /**
     * 创建企业微信成员
     * 并添加到代理商的部门下
     * @param userAccount 账号(唯一标识id)
     * @param userName 用户名
     * @param phone 电话号码
     * @return 0 成功
     */
    public Integer createMember(String userAccount, String userName, String phone){
        Map<String, Object> paramsMap = new HashMap();
        ArrayList array = new ArrayList();
        array.add(3);
        paramsMap.put("userid", userAccount);//成员UserID。对应管理端的帐号，企业内必须唯一
        paramsMap.put("name", userName);//成员名称
        paramsMap.put("alias", userName);//成员别名
        paramsMap.put("mobile", phone);//手机号码。企业内必须唯一
        paramsMap.put("department", array);//成员所属部门id列表
        /**
         * 获取token
         */
        getAccessToken(2);
        String requestUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=%s", ACCESS_TOKEN);
        Map<String, Object> resultMap = sendRequest(requestUrl, paramsMap, "POST");
        if ((Integer) resultMap.get("errcode") == 0) {
            return 0;
        }else {
            if((Integer)resultMap.get("errcode") == 42001){//access_token已过期
                //token过期，重新请求
                ACCESS_TOKEN = getAccessToken(2);
                createMember(userAccount, userName, phone);
            }else {
                return (Integer) resultMap.get("errcode");
            }
            return 0;
        }
    }

    /**
     * 删除企业微信成员
     * @param userAccount 企业微信账号
     * @return
     * @throws Exception
     */
    public Boolean deleteMember(String[] userAccount)throws Exception{
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("useridlist",userAccount);
        String requestUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=%s", ACCESS_TOKEN);
        Map<String, Object> resultMap = sendRequest(requestUrl, paramsMap, "POST");
        Integer code = (Integer) resultMap.get("errcode");
        if(code == 0){
            return true;
        }else {
            if (code == 42001 || code == 40014){
                //token过期，重新请求
                ACCESS_TOKEN = getAccessToken(2);
                deleteMember(userAccount);
            }else{
                throw new Exception(String.format("删除失败,返回全局错误码为:%s",resultMap.get("errcode").toString()));
            }
        }
        return true;
    }

    public Boolean deleteMember1(String userAccount)throws Exception{

        String requestUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=%s&userid=%s", ACCESS_TOKEN,userAccount);
        Map<String, Object> resultMap = sendRequest(requestUrl,null, "GET");
        Integer code = (Integer) resultMap.get("errcode");
        if(code == 0){
            return true;
        }else {
            if (code == 42001 || code == 40014){
                //token过期，重新请求
                ACCESS_TOKEN = getAccessToken(2);
                deleteMember1(userAccount);
            }else{
                throw new Exception(String.format("删除失败,返回全局错误码为:%s",resultMap.get("errcode").toString()));
            }
        }
        return true;
    }

    /**
     * 消息推送
     *
     * @param userAccount 用户的账号id
     * @param pushMessage 推送的消息
     * @return
     */
    public Boolean pushMessage(String userAccount, String pushMessage) throws Exception {
        Map<String, Object> paramsMap = new HashMap();


        Map<String, String> contentMap = new HashMap<>();
        contentMap.put("content", pushMessage);

        paramsMap.put("touser", userAccount);//推送的用户
        paramsMap.put("msgtype", "text");//文本消息推送通知
        paramsMap.put("agentid", agentId);//后台应用标识id
        paramsMap.put("text", JSON.toJSON(contentMap));//消息内容，最长不超过2048个字节
        paramsMap.put("safe", 0);//表示是否是保密消息，0表示否，1表示是，默认0

        String requestUrl = String.format("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s", ACCESS_TOKEN);

        Map<String, Object> resultMap = sendRequest(requestUrl, paramsMap, "POST");
        Integer code = (Integer) resultMap.get("errcode");
        //System.out.println("返回的code=================="+code);
        if (code == 0) {
            return true;
        } else {
            if (code == 42001 || code == 40014){
                //token过期，重新请求
                ACCESS_TOKEN = getAccessToken(1);
                pushMessage(userAccount, pushMessage);
            }else{
                throw new Exception(String.format("推送消息失败,返回全局错误码为:%s",resultMap.get("errcode").toString()));
            }
        }
        return true;
    }
    /*public static void main(String[] args) throws Exception {
        String message = "充值订单:\n玩家ID:%s\n玩家昵称:%s\n充值金额:%s元\n充值时间:%s";
        System.out.println(PushUtils.getInstance().pushMessage("15800070024", String.format(message,"1234","今晚打老虎","2","2018-08-08 12:12:12")));
        //System.out.println(PushUtils.getInstance().createMember("123456","userName","15800070014","2"));
    }*/
}
